<?php

namespace app\common\controller;

use think\facade\Env;

/**
 * 微信登录
 */
class ApiWechatLogin
{

  /**
   * 初始化方法
   */
  protected function initialize() {}


  public function login($code = '')
  { 
    $appId = Env::get('WECHAT.WECHAT_APPID');
    $appSecret = Env::get('WECHAT.WECHAT_SECRET');
    // 获取前端传递的 code 和用户信息
    $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appId . "&secret=" . $appSecret . "&js_code={$code}&grant_type=authorization_code";
    // 发送请求获取 openid 和 session_key
    $response = file_get_contents($url);
    
    $data = json_decode($response, true);
    if (isset($data['openid'])) {
      $openid = $data['openid'];
      $session_key = $data['session_key'];
      return [
        'status' => 'success',
        'session_key' => $session_key,
        'openid' => $openid,
        'unionid' =>''
      ];
    } else {
      return [
        'status' => 'error',
        'message' => 'Failed to get session key and openid.',
      ];
    }
  }
}
